package net.qiqb.spring.tx;

import net.qiqb.core.domain.persist.annotation.PersistOperation;
import net.qiqb.core.domain.persist.annotation.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

public class SpringTransaction implements Transaction {

    private PlatformTransactionManager transactionManager;


    @Override
    public void commit(PersistOperation persistOperation) {
        DefaultTransactionDefinition transactionDefinition = new DefaultTransactionDefinition();
        transactionDefinition.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);

        // 获取事务状态
        TransactionStatus transactionStatus = transactionManager.getTransaction(transactionDefinition);
        try {
            persistOperation.operate();
            // 如果一切正常，提交事务
            transactionManager.commit(transactionStatus);
        } catch (Exception e) {
            // 如果发生异常，回滚事务
            transactionManager.rollback(transactionStatus);
            throw e; // 可以选择捕获并处理异常，或者将异常继续抛出
        }
    }

    @Autowired
    public void setTransactionManager(PlatformTransactionManager transactionManager) {
        this.transactionManager = transactionManager;
    }
}
